package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XCPlusException;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTableService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author:王亚栋
 * @Date:2023/8/26 17:38
 * @Version:1.0
 * 选课相关接口实现
 */
@Service
@Slf4j(topic = "MyCourseTableServiceImpl")
public class MyCourseTableServiceImpl implements MyCourseTableService {

    /**
     * 选课相关Mapper
     */
    @Autowired
    private XcChooseCourseMapper xcChooseCourseMapper;

    /**
     * 我的课程表Mapper
     */
    @Autowired
    private XcCourseTablesMapper xcCourseTablesMapper;

    /**
     * 内容管理服务Feign服务端
     */
    @Autowired
    private ContentServiceClient contentServiceClient;

    @Transactional
    @Override
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //选课调用内容管理查询课程的收费规则
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);

        if (coursepublish == null){

            XCPlusException.cast("课程不存在！");
        }
        //收费规则
        String charge = coursepublish.getCharge();
        //选课记录
        XcChooseCourse chooseCourse = null;

        //如果课程免费，向 选课记录表，我的课程表 写数据
        if (charge.equals("201000")){
            //向 选课记录表 写入数据
            chooseCourse = addFreeCourse(userId, coursepublish);
            //向 我的课程表 写入数据
            XcCourseTables courseTables = addCourseTables(chooseCourse);
        }else {

            //如果课程收费，向 选课记录表 写数据
            chooseCourse = addChargeCourse(userId, coursepublish);
        }



        //判断学生的学习资格
        XcCourseTablesDto learningStatus = getLearningStatus(userId, courseId);

        //构造返回值

        XcChooseCourseDto returnDto = new XcChooseCourseDto();

        BeanUtils.copyProperties(chooseCourse,returnDto);

        //设置学习资格状态
        returnDto.setLearnStatus(learningStatus.getLearnStatus());

        return returnDto;
    }

    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {

        XcCourseTablesDto xcCourseTablesDto = null;

        //查询我的课程表,如果查不到则说明没有选课
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);

        if (xcCourseTables == null){

            xcCourseTablesDto = new XcCourseTablesDto();

            xcCourseTablesDto.setLearnStatus("702002");

            return xcCourseTablesDto;
        }
        //如果查到了，需判断是否过期
        boolean before = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if (before) {
            //过期

            xcCourseTablesDto.setLearnStatus("702003");

            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);

            return xcCourseTablesDto;
        }else {

            //可以正常学习
            xcCourseTablesDto.setLearnStatus("702001");

            BeanUtils.copyProperties(xcCourseTables,xcCourseTablesDto);

            return xcCourseTablesDto;

        }

    }

    /**
     * 添加收费课程-向选课记录表写入数据
     * @param userId
     * @param coursepublish
     * @return
     */
    private XcChooseCourse addChargeCourse(String userId, CoursePublish coursepublish) {

        //课程Id
        Long courseId = coursepublish.getId();

        //判断 如果存在免费的课程记录 且 选课状态为成功，直接返回
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(XcChooseCourse::getUserId,userId);
        queryWrapper.eq(XcChooseCourse::getCourseId,courseId);
        //收费课程
        queryWrapper.eq(XcChooseCourse::getOrderType,"700002");
        //待支付
        queryWrapper.eq(XcChooseCourse::getStatus,"701002");

        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);

        if (xcChooseCourses.size() > 0){

            return xcChooseCourses.get(0);
        }

        // 向选课记录表写数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();

        xcChooseCourse.setCourseId(courseId);
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        //收费课程
        xcChooseCourse.setOrderType("700002");
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setValidDays(365);
        //收费课程-默认待支付
        xcChooseCourse.setStatus("701002");
        //有效期开始时间
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        //有效期的结束时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));

        //插入数据
        int insertResult = xcChooseCourseMapper.insert(xcChooseCourse);

        if (insertResult < 1){

            XCPlusException.cast("添加选课记录失败！");
        }

        return xcChooseCourse;
    }

    /**
     * 添加 我的课程表 记录
     * @param xcChooseCourse
     * @return
     */
    private XcCourseTables addCourseTables(XcChooseCourse xcChooseCourse) {

        //选课成功了才可以添加到我的课程表
        String status = xcChooseCourse.getStatus();

        if (!status.equals("701001")){

            XCPlusException.cast("选课没有成功所以不能添加到我的课程表中！");
        }
        XcCourseTables xcCourseTables = getXcCourseTables(xcChooseCourse.getUserId(),xcChooseCourse.getCourseId());

        if (xcCourseTables != null){
            return xcCourseTables;
        }
        //向我的课程表插入数据
        xcCourseTables = new XcCourseTables();

        BeanUtils.copyProperties(xcChooseCourse,xcCourseTables);

        //记录选课表中的主键
        xcCourseTables.setChooseCourseId(xcChooseCourse.getId());
        //课程类型
        xcCourseTables.setCourseType(xcChooseCourse.getOrderType());
        //更新时间
        xcCourseTables.setUpdateDate(LocalDateTime.now());

        //插入数据
        int insertResult = xcCourseTablesMapper.insert(xcCourseTables);

        if (insertResult < 1){

            XCPlusException.cast("添加我的课程表记录失败！");
        }

        return xcCourseTables;
    }

    /**
     * 根据课程和用户查询 我的课程表中某一门课程
     * @param userId
     * @param courseId
     * @return
     */
    private XcCourseTables getXcCourseTables(String userId, Long courseId) {

        LambdaQueryWrapper<XcCourseTables> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(XcCourseTables::getUserId,userId);
        queryWrapper.eq(XcCourseTables::getCourseId,courseId);

        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(queryWrapper);

        return xcCourseTables;
    }

    /**
     * TODO 添加免费课程，免费课程加入 选课记录表，我的课程表
     * @param userId
     * @param coursePublish
     * @return
     */
    private XcChooseCourse addFreeCourse(String userId,CoursePublish coursePublish){

        //课程Id
        Long courseId = coursePublish.getId();

        //判断 如果存在免费的课程记录 且 选课状态为成功，直接返回
        LambdaQueryWrapper<XcChooseCourse> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(XcChooseCourse::getUserId,userId);
        queryWrapper.eq(XcChooseCourse::getCourseId,courseId);
        //免费课程
        queryWrapper.eq(XcChooseCourse::getOrderType,"700001");
        //选课成功
        queryWrapper.eq(XcChooseCourse::getStatus,"701001");

        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(queryWrapper);

        if (xcChooseCourses.size() > 0){

            return xcChooseCourses.get(0);
        }

        // 向选课记录表写数据
        XcChooseCourse xcChooseCourse = new XcChooseCourse();

        xcChooseCourse.setCourseId(courseId);
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursePublish.getCompanyId());
        xcChooseCourse.setCourseName(coursePublish.getName());
        xcChooseCourse.setOrderType("700001");
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCoursePrice(coursePublish.getPrice());
        xcChooseCourse.setValidDays(365);
        //选课成功
        xcChooseCourse.setStatus("701001");
        //有效期开始时间
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        //有效期的结束时间
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));

        //插入数据
        int insertResult = xcChooseCourseMapper.insert(xcChooseCourse);

        if (insertResult < 1){

            XCPlusException.cast("添加选课记录失败！");
        }

        return xcChooseCourse;
    }
}
